<%@page isErrorPage="true" %>
<%@page errorPage="fallback-error.jsp" %>

<%@page session="false" %>

<%@page import="com.googlecode.afdbaccess.web.common.exception.GuiLayerException" %>
<%@page import="com.googlecode.afdbaccess.cache.resultconversion.exceptions.ConverterRuntimeException"%>

<%@page import="com.googlecode.afdbaccess.web.common.exception.GuiLayerJsonFormattedException"%>
<%@page import="com.googlecode.afdbaccess.web.common.util.JsonPageUtil"%>

<%@page import="com.googlecode.afdbaccess.web.common.errorhelp.ExceptionToString"%>
<%@page import="com.googlecode.afdbaccess.web.common.errorhelp.UniqueIdGenerator"%>

<%@page import="org.apache.log4j.Logger" %>
<%@page import="java.sql.SQLException" %>

<%@page import="java.util.Enumeration"%>

<%!
  private Throwable getMostInterestingExceptionFromNested(Throwable rootException) {
    Throwable currentException = rootException;
    
    while(currentException != null) {
        if(currentException instanceof GuiLayerException||
           currentException instanceof SQLException ||
           currentException instanceof ConverterRuntimeException) {
            return currentException;
        }
        
        currentException = currentException.getCause();
    }
    
    return rootException;
  }
%>

<%
  Logger log = Logger.getLogger(this.getClass());

  Enumeration<String> attributeNames = request.getHeaderNames();
  while(attributeNames.hasMoreElements()) {
      String attributeName = attributeNames.nextElement();
      String attributeValue = request.getHeader(attributeName);
      log.debug("Header " + attributeName + "=" + attributeValue);
  }

  boolean isJsonPage = JsonPageUtil.isJsonPage(request, response);

  if(exception == null) {
      exception = (Throwable)request.getAttribute("javax.servlet.error.exception");
  }
  
  Throwable mostInterestingException = getMostInterestingExceptionFromNested(exception);

  String stacktraceString = null;
  boolean showStacktrace = true;
  String message = "Unrecognized error.";
  String longMessage = null;
  String uniqueId = null;
  
  boolean isError = true;

  if(mostInterestingException != null) {
    message = mostInterestingException.getMessage();
  }
  
  if(mostInterestingException instanceof GuiLayerException) {
    GuiLayerException e = (GuiLayerException)mostInterestingException;
    
    response.setStatus(e.getHttpReturnCode());

    longMessage = " ";
    
    if(e.getLongMessage() != null) {
        longMessage = e.getLongMessage();
    }

    if(e.getShowStackTrace()) {
      uniqueId = new UniqueIdGenerator().getId();
      log.error("Uncaught exception reached errorpage (" + uniqueId + ")", exception);
      stacktraceString = ExceptionToString.getStackTraceAsString(exception);
    } else {
      // this means that the page that rethrew the exception has handled it, so no need to log it or show it to the user. Just show the error message.
      showStacktrace = false;

      log.debug("Handled exception sent to errorpage for display:", exception);
      
      if(isJsonPage) {
        String jsonStringPart = "";
        if(e instanceof GuiLayerJsonFormattedException) {
          jsonStringPart = ((GuiLayerJsonFormattedException)e).getJsonStringPart();
        }
        
        String tempLongMessage = (e.getLongMessage() != null)?e.getLongMessage():"";
%>
<jsp:forward page="/error/errormessage-json.jsp">
  <jsp:param name="message" value="<%= e.getMessage() %>" />
  <jsp:param name="longmessage" value="<%= tempLongMessage %>" />
  <jsp:param name="jsonstringpart" value="<%= jsonStringPart %>" />
</jsp:forward>
<%
      } else {
        stacktraceString = ExceptionToString.getStackTraceAsString(exception);
      }
    }
    
    isError = (e.getSeverity()!=GuiLayerException.Severity.INFO);
  } else {
    uniqueId = new UniqueIdGenerator().getId();
    if(exception != null) {
      log.error("Uncaught exception reached errorpage (" + uniqueId + ")", exception);
      stacktraceString = ExceptionToString.getStackTraceAsString(exception);
      
      if(message == null || message.trim().equals("") == true) {
          message = exception.getMessage();
      }

      if(message == null || message.trim().equals("") == true) {
          message = exception.toString();
      }
    } else {
      log.error("Uncaught exception reached backwebb errorpage (" + uniqueId + ") but exception is null?", exception);

      message = "Http status: " + response.getStatus();
      longMessage = "Detailed error information is not available (exception is null).";
      
      if(isJsonPage) {
%>
<jsp:forward page="/error/errormessage-json.jsp">
  <jsp:param name="message" value="<%= message %>" />
  <jsp:param name="longmessage" value="<%= longMessage %>" />
</jsp:forward>
<%
      }
    }
  }
%>

<jsp:forward page="/error/errormessage.jsp">
  <jsp:param name="error" value="<%= isError %>" />
  <jsp:param name="pagetitle" value="Error message" />
  <jsp:param name="header" value="<%= message %>" />
  <jsp:param name="message" value="<%= longMessage %>" />
  <jsp:param name="stacktrace" value="<%= stacktraceString %>" />
  <jsp:param name="hidestacktrace" value="<%= !showStacktrace %>" />
  <jsp:param name="uniqueid" value="<%= uniqueId %>" />
</jsp:forward>
